package com.webtest.mvctest2.dao.impl;

import com.webtest.mvctest2.dao.CriteriaCustomer;
import com.webtest.mvctest2.dao.CustomerDao;
import com.webtest.mvctest2.dao.DaoBase;
import com.webtest.mvctest2.model.Customer;

import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/7/26 16:22
 */
public class CustomerDaoJdbcImpl extends DaoBase<Customer> implements CustomerDao {
    @Override
    public List<Customer> getAll() {
        String sql = "SELECT id, name, address, phone FROM customer";
        return getForList(sql);
    }

    @Override
    public void save(Customer customer) {
        String sql = "INSERT INTO customer(name, address, phone) VALUES(?,?,?)";
        update(sql, customer.getName(), customer.getAddress(), customer.getPhone());
    }

    @Override
    public Customer get(Integer id) {
        String sql = "SELECT id, name, address,phone FROM customer WHERE id=?";
        return get(sql, id);
    }

    @Override
    public void delete(Integer id) {
        String sql = "DELETE FROM customer WHERE id=?";
        update(sql, id);
    }

    @Override
    public void update(Customer customer) {
        String sql = "UPDATE customer SET name=?, address=?, phone=? WHERE id=?";
        update(sql, customer.getName(), customer.getAddress(), customer.getPhone(), customer.getId());
    }

    @Override
    public List<Customer> getForListWithCriteriaCustomer(CriteriaCustomer param) {
        String sql = "SELECT c.id, c.name, c.address, c.phone FROM customer c WHERE c.name like '?1' AND address like '?2' AND phone like '?3'";
        sql = sql.replace("?1", param.getName()).replace("?2", param.getAddress()).replace("?3", param.getPhone());
        return getForList(sql);
    }

    @Override
    public long getCountWithName(String name) {
        String sql = "SELECT COUNT(id) FROM customer WHERE name=?";
        return Long.parseLong(getForValue(sql, name).toString());
    }
}
